<template>
	<view class="page w-full h-100vh bg-f5f5f5">
		<view class="w-690 m-auto">
			<wd-form ref="form" :model="formData">
				<!-- 头像上传 -->
				<wd-cell title="头像" center prop="avatar">
					<button open-type="chooseAvatar" @chooseavatar="handleChooseAvatar" class="avatar-button">
						<wd-img size="large" :src="formData.avatar" :width="100" :height="100" />
					</button>
				</wd-cell>

				<wd-input type="nickname" label="昵称" prop="nickName" v-model="formData.nickName" size="large"
					label-width="100px" placeholder="昵称" align-right @blur="handleChooseNick"
					:rules="[{ required: true, message: '请填写昵称' }]" />

				<wd-input label="真实姓名" prop="realName" v-model="formData.realName" size="large" label-width="100px"
					placeholder="真实姓名" align-right :rules="[{ required: true, message: '请填写真实姓名' }]" />

				<wd-input label="手机号" prop="phone" v-model="formData.phone" size="large" label-width="100px"
					placeholder="手机号" align-right :rules="[{ required: true, message: '请填写手机号' }]" />

				<wd-input label="公司名称" prop="companyName" v-model="formData.companyName" size="large"
					label-width="100px" placeholder="公司名称" align-right
					:rules="[{ required: false, message: '请填写公司名称' }]" />

				<wd-input label="个性签名" prop="selfNote" v-model="formData.selfNote" size="large" label-width="100px"
					placeholder="个性签名" align-right :rules="[{ required: false, message: '请填写个性签名' }]" />

				<wd-cell title="是否显示微信二维码" center prop="wxQrcodeState">
					<wd-switch v-model="formData.wxQrcodeState" :active-value="1" :inactive-value="0" />
				</wd-cell>

				<wd-cell title="微信二维码" :isLink="formData.wxQrcode ? false :true" center prop="wxQrcode" v-if="formData.wxQrcodeState == 1">
					<button @click="reUploadQr" class="avatar-button">
						<wd-img size="large" :src="formData.wxQrcode" :width="100" :height="100" v-if="formData.wxQrcode"/>
            <text class="f-30 text-999" v-else>请选择图片上传</text>
					</button>
				</wd-cell>

			</wd-form>
		</view>

		<!-- 保存按钮 -->
		<view class="save-btn fixed b-30 pl-30 pr-30 w-full">
			<wd-button type="primary" size="large" block @click="handleSave">保存修改</wd-button>
		</view>

	</view>
</template>

<script setup>
	import { ref } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	import { useUserStore } from '@/store/user'

	const { api_post_updateMyInfo, uploadFile, api_get_myInfo } = useRequest()
	const { proxy } = getCurrentInstance()
	const userStore = useUserStore()
	const { userInfo } = storeToRefs(userStore)

	// 表单数据
	const formData = ref({
		nickName: '',
		realName: '',
		phone: '',
		avatar: '',
		companyName: '',
		selfNote: '',
		wxQrcode: '',
		wxQrcodeState: null
	})

	// 加载用户数据
	onLoad(() => {
		loadUserData()
	})

	// 加载用户数据
	const loadUserData = () => {
		Object.keys(formData.value).forEach((key) => {
			if (userInfo.value[key]) {
				formData.value[key] = userInfo.value[key]
			}
		})
	}

	// 选择头像
	const handleChooseAvatar = async (e) => {
		const res = await uploadFile(e.detail.avatarUrl)
		if (res.src) {
			formData.value.avatar = res.src
		}
	}

	const reUploadQr = () => {
		uni.chooseImage({
			count: 1, // 最多可选图片数量，默认 9
			sizeType: ['original'], // 可以指定是原图还是压缩图，默认二者都有
			success: async (res) => {
				const result = await uploadFile(res.tempFilePaths[0])
				formData.value.wxQrcode = result.src
			},
			fail: (err) => {
				console.error('选择图片失败:', err);
			}
		});
	}

	const handleChooseNick = (e) => {
		formData.value.nickName = e.value
	}

	// 保存修改
	const form = ref()
	const handleSave = async () => {
		form.value
			.validate()
			.then(async ({ valid, errors }) => {
				if (valid) {
					try {
						uni.showLoading({ title: '保存中...' })

						const res = await api_post_updateMyInfo(formData.value)
						uni.hideLoading()
						if (res.code === 0) {
							uni.showToast({
								title: '保存成功',
								icon: 'success'
							})
							api_get_myInfo()
							setTimeout(() => {
								uni.navigateBack()
							}, 1500)
						}
					} catch (error) {
						uni.hideLoading()
						uni.showToast({
							title: '保存失败',
							icon: 'none'
						})
						console.error('保存失败:', error)
					}

				}
			})
			.catch((error) => {
				console.log(error, 'error')
			})
	}
</script>

<style lang="scss" scoped>
	.avatar-button {
		padding: 0;
		margin: 0;
		background: transparent;
		border: none;
		line-height: 1;

		&::after {
			border: none;
		}
	}
</style>